package yao.algorithm.personal;

import java.util.Stack;

public class BracketMatcher {
	
	
	public static void main(String[] args) {
		
		String mobile = "0001";
		char[] array = mobile.toCharArray();
		for(int i=0; i<array.length-3; i++) {
			if(array[i] == array[i+1] && array[i] != array[i+2] && array[i+2] == array[i+3]) {
				System.out.println("matched i=" + i);
				break;
			}
		}	
	}
	
	public boolean isMatchBrackets(String source) {
		if(source == null || source.trim().length() == 0) {
			throw new RuntimeException("source is null or length is zero");
		}
		Stack<Character> stack = new Stack<Character>();
		char[] charArray = source.toCharArray();
		for(int i = 0; i < charArray.length; i++) {
			char c = charArray[i];
			if(isLeftBrackets(c)) {
				stack.push(c);
			} else if(isRightBrackets(c)) {
				if(stack.isEmpty()) {
					return false;
				}
				stack.pop();
			} else {
				throw new RuntimeException("unknown error");
			}
		}		
		boolean isMatched = false;
		if(stack.isEmpty()) {
			isMatched = true;
		}
		return isMatched;
	}
	

	private boolean isRightBrackets(char c) {
		return c == ')';
	}

	private boolean isLeftBrackets(char c) {
		return c == '(';
	}
}
